package com.example.login_captcha_2.service.impl;


import com.example.login_captcha_2.consts.RedisKeyPrefixes;
import com.example.login_captcha_2.dto.UserLoginDTO;
import com.example.login_captcha_2.exception.GlobalException;
import com.example.login_captcha_2.redis.StringRedisUtils;
import com.example.login_captcha_2.restful.ResponseCode;
import com.example.login_captcha_2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private final StringRedisUtils stringRedisUtils;

    @Autowired
    public UserServiceImpl(StringRedisUtils stringRedisUtils) {
        this.stringRedisUtils = stringRedisUtils;
    }

    @Override
    public void login(UserLoginDTO loginDTO) {
        // 得到用户输入的验证码
        String code = loginDTO.getCode();

        // 获取正确的验证码
        String key = getCaptchaKey(loginDTO.getUuid());
        String realCode = stringRedisUtils.get(key);

        // 得到的验证码为空，则获取验证码到登录之间的时间已经过了3分钟，验证码过期已经被删除
        if (realCode == null) {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "验证码已失效，请重新获取~");
        }
        // 验证码校验
        if (!code.equalsIgnoreCase(realCode)) {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "验证码错误~");
        }

        /* 其它代码... */
    }

    /**
     * 拼接得到验证码的key
     * @param uuid 前端随机生成的uuid
     * @return String 验证码的key
     */
    private String getCaptchaKey(String uuid) {
        return RedisKeyPrefixes.PREFIX_CAPTCHA + uuid;
    }

}